package com.lzm.back.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzm.back.entity.File;
import com.lzm.back.mapper.FileMapper;
import jakarta.annotation.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
public class FileService {
    @Resource
    private FileMapper fileMapper;
    @Resource
    private ResourceLoader resourceLoader;
    public void upload(Long eventId,
                       String fileName,
                       String filePath, MultipartFile file) throws IOException {
        // 获取静态资源目录
//        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:static/files");
        java.io.File directory = new java.io.File("D:\\workspace\\BiYeSheji\\back\\src\\main\\resources\\static\\files");

        // 如果目录不存在，则创建它
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 构建文件路径
        Path destination = Paths.get(directory.getAbsolutePath(), String.valueOf(eventId), file.getOriginalFilename());
        if (!destination.getParent().toFile().exists()){
            destination.getParent().toFile().mkdirs();
        }

        // 保存文件
        Files.copy(file.getInputStream(), destination);
        // 插入数据库记录
        File record = new File();
        record.setEventId(eventId);
        record.setFileName(file.getOriginalFilename());
        record.setFilePath(destination.toString());
        fileMapper.insert(record);
        System.out.println("文件已保存到: " + destination);
    }

    public PageInfo<File> selectPage(String eventName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<File> fileList = fileMapper.selectByCondition(eventName);
        return PageInfo.of(fileList);
    }

    public void deleteFile(Long id) {
        //删除对应文件
        File file = selectFileById(id);
        if (file!=null) {
            fileMapper.deleteByPrimaryKey(id);
            String filePath = file.getFilePath();
            try {
                Files.deleteIfExists(Paths.get(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void deleteFileBaTch(List<Long> ids) {
        for (Long id : ids) {
            deleteFile(id);
        }
    }

    public File selectFileById(Long id) {
        return fileMapper.selectByPrimaryKey(id);
    }

    public void updateFile(File file) {
        fileMapper.updateByPrimaryKeySelective(file);
    }

    public org.springframework.core.io.Resource downloadFile(Long id) {
        // 根据文件ID获取文件路径，这里假设你有一个方法 getFileById 返回 File 对象
        File file = selectFileById(id);
        if (file == null) {
            throw new RuntimeException("文件不存在");
        }
        try {
            Path path = Paths.get(file.getFilePath());
            UrlResource resource = new UrlResource(path.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new RuntimeException("文件不存在或不可读");
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("文件路径错误", e);
        }
    }
}
